package com.gexiaobao.pigeon.ui.fragment.mine.organization.activity

import android.content.res.ColorStateList
import android.os.Bundle
import android.widget.LinearLayout
import android.widget.ListPopupWindow
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.model.bean.PassInfoBean
import com.gexiaobao.pigeon.app.model.bean.RaceInfoResponse
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.ActivityPassDetailBinding
import com.gexiaobao.pigeon.ui.adapter.MyPopPassAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogSingle
import com.gexiaobao.pigeon.ui.fragment.mine.organization.detail.FragmentListOfAwards
import com.gexiaobao.pigeon.ui.fragment.mine.organization.detail.FragmentLivePerformance
import com.gexiaobao.pigeon.ui.fragment.mine.organization.detail.FragmentOrgPassDetail
import com.gexiaobao.pigeon.ui.fragment.mine.organization.detail.FragmentPassDetailMine
import com.gexiaobao.pigeon.viewmodel.OrgDetailViewModel
import com.gexiaobao.pigeon.viewmodel.SharedViewModel
import com.google.android.material.tabs.TabLayout
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2024/5/29 15:00
 * @Describe    : 关卡详情
 */
class ActivityPassDetail : BaseActivity<OrgDetailViewModel, ActivityPassDetailBinding>() {

    private var mData: ArrayList<RaceInfoResponse.PassListBean> = arrayListOf()
    private var passId: Int = 0
    private var memberId: Int = 0
    private var raceId: Int = 0
    private var listPopupWindow: ListPopupWindow? = null
    private val mList: MutableList<String> = mutableListOf()

    private var mOrgIcon = ""
    private var mOrgName = ""
    private var mOrgRaceName = ""
    private var title = ""
    private var passStatus = ""
    private var mPassCreateType = 0
    private var mPassType = 0

    private val sharedViewModel: SharedViewModel by viewModels()

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        /** tabLayout去除点击背景 */
        mDatabind.tabLayout.tabRippleColor = ColorStateList.valueOf(ContextCompat.getColor(this, android.R.color.transparent))

        title = intent.getStringExtra("passName").toString()
        passId = intent.getIntExtra("passId", 0)
        memberId = intent.getIntExtra("memberId", 0)
        raceId = intent.getIntExtra("raceId", 0)
        mOrgIcon = intent.getStringExtra("orgIcon").toString()
        mOrgName = intent.getStringExtra("orgName").toString()
        mOrgRaceName = intent.getStringExtra("raceName").toString()
        passStatus = intent.getStringExtra("passStatus").toString()
        mPassCreateType = intent.getIntExtra("passCreateType", 0)
        mPassType = intent.getIntExtra("passType", 0)

        mDatabind.tvPassTitle.text = title
        mData = intent.getParcelableArrayListExtra("data")!!
        selectBox(mData)//添加数据，初始化ListPopupWindow
        initTabLayout()

        listPopupWindow?.setOnItemClickListener { _, _, position, _ ->
            passId = mData[position].id
            title = mData[position].passName
            passByValueToFragment()
            mDatabind.tvPassTitle.text = mList[position]
            listPopupWindow!!.dismiss()
        }
    }

    private fun passByValueToFragment() {
        val bean = PassInfoBean(raceId = raceId, id = passId, titleName = title)
        sharedViewModel.setData(bean)
    }

    private fun selectBox(data: ArrayList<RaceInfoResponse.PassListBean>?) {
        mList.clear()
        if (data != null) {
            if (data.isNotEmpty()) {
                data.forEach { item ->
                    mList.add(item.passName)
                }
            }
        }
        /** 初始化ListPopupWindow，适配 */
        listPopupWindow = ListPopupWindow(this)
        val adapter = MyPopPassAdapter(this, mList)
        listPopupWindow?.setAdapter(adapter)
        listPopupWindow?.anchorView = mDatabind.tvPassTitle//设置ListPopupWindow的锚点，关联mButton位置
        listPopupWindow?.width = LinearLayout.LayoutParams.MATCH_PARENT
        listPopupWindow?.height = LinearLayout.LayoutParams.WRAP_CONTENT
        listPopupWindow?.isModal = true
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvPassTitle, mDatabind.ivVisitBack) {
            when (it) {
                mDatabind.ivVisitBack -> {
                    finish()
                }

                mDatabind.tvPassTitle -> {
                    listPopupWindow?.show()
                }
            }
        }
    }

    private fun initTabLayout() {
        if (mPassCreateType == 2) {
            mDatabind.tabLayout.isVisible = false
            val tab1 = mDatabind.tabLayout.newTab().setText(getString(R.string.Live_performance))
            mDatabind.tabLayout.addTab(tab1)
        } else {
            mDatabind.tabLayout.isVisible = true
            val tab1 = mDatabind.tabLayout.newTab().setText(getString(R.string.Live_performance))
            mDatabind.tabLayout.addTab(tab1)
            val tab2 = mDatabind.tabLayout.newTab().setText(getString(R.string.List_of_awards))
            mDatabind.tabLayout.addTab(tab2)
            val tab3 = mDatabind.tabLayout.newTab().setText(getString(R.string.My_grade))
            mDatabind.tabLayout.addTab(tab3)
            val tab4 = mDatabind.tabLayout.newTab().setText(getString(R.string.pass_detail))
            mDatabind.tabLayout.addTab(tab4)
        }
        mDatabind.tabLayout.addOnTabSelectedListener(object : TabLayout.BaseOnTabSelectedListener<TabLayout.Tab> {
            override fun onTabReselected(p0: TabLayout.Tab) {}
            override fun onTabUnselected(p0: TabLayout.Tab) {}

            override fun onTabSelected(p0: TabLayout.Tab) {
                replaceFragments(p0.position)
            }
        })
        replaceFragments(0)
    }

    private fun replaceFragments(position: Int) {
        supportFragmentManager.beginTransaction().apply {
            when (position) {
                0 -> replace(R.id.passDetailContainer, FragmentLivePerformance.newInstance(raceId, passId, title, mPassType, mPassCreateType))//成绩直播
                1 -> {
                    if (memberId == 0) {
                        showDialogNoMember()
                        return
                    }
                    replace(R.id.passDetailContainer, FragmentListOfAwards.newInstance(passId))//奖项列表
                }

                2 -> {
                    if (memberId == 0) {
                        showDialogNoMember()
                        return
                    }
                    replace(
                        R.id.passDetailContainer,
                        FragmentPassDetailMine.newInstance(memberId, passId, raceId, mOrgName, mOrgRaceName, mOrgIcon)
                    )//我的成绩
                }

                3 -> replace(R.id.passDetailContainer, FragmentOrgPassDetail.newInstance(raceId, passId, title, passStatus)) //关卡详情
            }
        }.commitAllowingStateLoss()
    }

    private fun showDialogNoMember() {
        val dialog = RxDialogSingle(this)
        dialog.setTitle(getString(R.string.no_member_and_can_not_look))
        dialog.setSureListener {
            selectTabAt(0)
            dialog.dismiss()
        }
        dialog.setCanceledOnTouchOutside(false)
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun selectTabAt(position: Int) {
        // 确保 position 在 tabLayout 的 tab 数量范围内
        if (position in 0 until mDatabind.tabLayout.tabCount) {
            val tab = mDatabind.tabLayout.getTabAt(position)
            tab?.select() // 选择指定的 tab
        }
    }

}